﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using YunSpace.Data.Extensions;
using YunSpace.Domain.Entity.MiniSite;

namespace YunSpace.Application.MiniSite
{
    public class CommonApp
    {
        MySqlDbHelper db = new MySqlDbHelper();

        #region Init
        private TableEntity GetTable(string keyName)
        {
            TableEntity result = default(TableEntity);

            var sqlStr = @"select F_Id, F_KeyName, F_SQL, F_PARAMS from Tables_Settings where F_KeyName = @keyName";
            var param = new MySqlParameter[] {
                new MySqlParameter("@keyName", MySqlDbType.VarChar, 50){ Value = keyName }
            };
            var dt = db.GetDataTable(sqlStr, param);
            if (dt.Rows.Count == 1)
            {
                var row = dt.Rows[0];
                result = new TableEntity()
                {
                    F_Id = row["F_Id"].ToString(),
                    F_KeyName = row["F_KeyName"].ToString(),
                    F_SQL = row["F_SQL"].ToString(),
                    F_PARAMS = row["F_PARAMS"].ToString()
                };
            }

            return result;
        }

        private string GetSql(string keyName) {
            var sqlStr = @"select F_SQL from Tables_Settings where F_KeyName = @keyName";
            var param = new MySqlParameter[] {
                new MySqlParameter("@keyName", MySqlDbType.VarChar, 50){ Value = keyName }
            };
            var result = db.GetFieldValue(sqlStr, param);

            return result;
        }

        #endregion


        /// <summary>
        /// 获取数据集合
        /// </summary>
        public DataTable GetList(string keyName, Dictionary<string, dynamic> input)
        {
            var sqlStr = GetSql(keyName);

            var param = input.Select(p => new MySqlParameter("@" + p.Key, p.Value)).ToArray();
            var dt = db.GetDataTable(sqlStr, param);
            return dt;
        }

        /// <summary>
        /// 获取数据集合
        /// </summary>
        public DataTable GetList(string keyName)
        {
            var sqlStr = GetSql(keyName);
            var dt = db.GetDataTable(sqlStr);
            return dt;
        }

    }
}
